<?php
  
class Upload_Helper
{
 
private $errors;
private $pathToFull;
private $pathToThumb;
 
     // загружать можно только jpg
     public function uploadPhoto($userId)
     {
        if (!preg_match('/[.](jpg)$/' , $_FILES['userfile']['name'])) {
            $this->errors = WRONG_FILE_FORMAT;
            return false;
        } else {
            $uploadDir = FULL_PICTURE_PATH . 'id' . $userId;
            $this->pathToFull = $uploadDir . '/' . basename($_FILES['userfile']['name']);
            if(!file_exists(SITE_PATH . $uploadDir)){
                if(!mkdir(SITE_PATH . $uploadDir)) {
                    $this->errors = CREATE_DIRECTORY_ERROR  ;
                    return false;
                }
            }
            if(!move_uploaded_file($_FILES['userfile']['tmp_name'], SITE_PATH . $this->pathToFull )){
                $this->errors = UPLOAD_ERROR;
                return false;
            } else {
                 return $this->createThumbnail($userId);
            } 
        }   
     }
       
     public function createThumbnail($userId, $size = 200)
     {
        
        $image = imagecreatefromjpeg(SITE_PATH . $this->pathToFull);
          
        $ox = imagesx($image);
        $oy = imagesy($image);
        $ny = floor($oy * ($size / $ox)); 
        $nm = imagecreatetruecolor($size, $ny); 
        imagecopyresized($nm, $image, 0,0,0,0,$size,$ny,$ox,$oy);
        
        $uploadThumbDir = THUMB_PICTURE_PATH . 'id' . $userId  ;
        $this->pathToThumb = $uploadThumbDir . '/' . basename($this->pathToFull);

        if(!file_exists(SITE_PATH . $uploadThumbDir)) {
            if(!mkdir(SITE_PATH . $uploadThumbDir)) {
                $this->errors = CREATE_DIRECTORY_ERROR;
                return false;
            } 
        }
        if(!imagejpeg($nm, SITE_PATH . $this->pathToThumb , 100)) {
             $this->errors = UPLOAD_ERROR;
             return false;
        } else {
             return true;
        }
     }
     public function getErrors()
     {
        return $this->errors;   
     }
     public function getArray()
     {
        $objArr = get_object_vars($this);
        return $objArr;
     }
    
    
}
